package com.dhgate.spu.analysis.stat;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;

import com.dhgate.spu.analysis.consts.SysConsts;
import com.dhgate.spu.analysis.init.InitDbConfig;
import com.dhgate.spu.analysis.init.InitParameter;

/**
 * @author: 
 * @create: 2014-2-24 下午5:25:47
 * @description:
 */
public class StatXtractBrandItemMain {
	public static void main(String[] args) throws Exception {
		// 初始化基本配置参数
		InitParameter.init();
		// 读取数据库初始化配置
		InitDbConfig.init();
	

		String fl[] = { "itemcode" };
		SolrQuery solrQuery = new SolrQuery();
		solrQuery.setQuery("*:*");
		solrQuery.setFields(fl);
		solrQuery.setRows(100000);

		QueryResponse qr = SysConsts.SOLR_SERVER.query(solrQuery);
		long allItemNum = qr.getResults().getNumFound();
		
		
		doStat("extByBrandAndModel","品牌+型号+产品标题提取品牌的产品数量(品牌和型号交集):",true,allItemNum);
		doStat("extByBrand","品牌+产品标题提取品牌的产品数量:",false,allItemNum);
		doStat("extByModel","品牌的型号+产品标题提取品牌的产品数量:",true,allItemNum);
	}

	private static void doStat(String brandtype, String statType, boolean keyContainModel,long allItemNum) throws SolrServerException {
		String fl[] = { "itemcode", "brand", "model" };
		SolrQuery solrQuery = new SolrQuery();
		solrQuery.setQuery("brandtype:"+brandtype);
		solrQuery.setFields(fl);
		solrQuery.setRows(100000);

		QueryResponse qr = SysConsts.SOLR_SERVER.query(solrQuery);

		long numFound = qr.getResults().getNumFound();
		Map<String,List<String>> brandModelMap = new HashMap<String,List<String>>();
		
		for(SolrDocument doc : qr.getResults()){
			String key = ""+doc.get("brand");
			if(keyContainModel){
				key = key +","+doc.get("model");
			}
			List<String> icList = brandModelMap.get(key);
			if (icList==null){
				icList = new ArrayList<String>();
				brandModelMap.put(key, icList);
			}
			icList.add(""+doc.get("itemcode"));
		}
		
		Iterator<String> it= brandModelMap.keySet().iterator();
		System.out.println("*********************************************************************");
		System.out.println();
		System.out.println(statType+numFound+"  占比:"+(numFound*100.0f/allItemNum)+"%");
		System.out.println((keyContainModel ? "包含品牌+型号数量:" : "包含品牌:")+brandModelMap.size());
		int count = 1;
		while(it.hasNext()){
			String key = it.next();
			StringBuffer icSB = new StringBuffer();
			int icNum = 0;
			for(String ic : brandModelMap.get(key)){
				icSB.append(ic+",");
				icNum++;
			}
			
			System.out.println("num"+count+":"+key+"(产品数量="+icNum+")"+":"+icSB.substring(0,icSB.length()-1));
			count++;
		}
	}
}
